package com.buaa.divinationmaster;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.buaa.divinationmaster.algorithm.TarotAlgorithm;
import com.buaa.divinationmaster.manager.DatabaseManager;
import com.buaa.divinationmaster.model.DivinationRecord;
import com.buaa.divinationmaster.model.TarotCard;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 塔罗牌占卜结果展示页面
 * 显示完整的占卜结果、解读和操作选项
 */
public class TarotResultActivity extends AppCompatActivity {
    
    private TextView tvQuestion, tvSpreadType, tvTimestamp, tvInterpretation;
    private Button btnSave, btnShare, btnNewReading, btnViewCards;
    
    private String question;
    private String spreadType;
    private String interpretation;
    private long timestamp;
    private String cardsInfo;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tarot_result);
        
        setupToolbar();
        initViews();
        loadResultData();
        setupClickListeners();
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("占卜结果");
        }
    }
    
    private void initViews() {
        tvQuestion = findViewById(R.id.tvQuestion);
        tvSpreadType = findViewById(R.id.tvSpreadType);
        tvTimestamp = findViewById(R.id.tvTimestamp);
        tvInterpretation = findViewById(R.id.tvInterpretation);
        btnSave = findViewById(R.id.btnSave);
        btnShare = findViewById(R.id.btnShare);
        btnNewReading = findViewById(R.id.btnNewReading);
        btnViewCards = findViewById(R.id.btnViewCards);
    }
    
    private void loadResultData() {
        Intent intent = getIntent();
        question = intent.getStringExtra("question");
        spreadType = intent.getStringExtra("spreadType");
        interpretation = intent.getStringExtra("interpretation");
        timestamp = intent.getLongExtra("timestamp", System.currentTimeMillis());
        cardsInfo = intent.getStringExtra("cards");
        
        // 显示数据
        tvQuestion.setText("问题：" + question);
        tvSpreadType.setText("牌阵：" + getSpreadDisplayName(spreadType));
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        tvTimestamp.setText("占卜时间：" + sdf.format(new Date(timestamp)));
        
        tvInterpretation.setText(interpretation);
    }
    
    private String getSpreadDisplayName(String spreadType) {
        try {
            TarotAlgorithm.SpreadType type = TarotAlgorithm.SpreadType.valueOf(spreadType);
            return type.getName();
        } catch (Exception e) {
            return spreadType;
        }
    }
    
    private void setupClickListeners() {
        btnSave.setOnClickListener(v -> saveReading());
        btnShare.setOnClickListener(v -> shareReading());
        btnNewReading.setOnClickListener(v -> startNewReading());
        btnViewCards.setOnClickListener(v -> viewDetailedCards());
    }
    
    private void saveReading() {
        try {
            // 创建占卜记录
            DivinationRecord record = new DivinationRecord(
                "tarot", 
                question, 
                cardsInfo, 
                interpretation, 
                timestamp
            );
            
            // 保存到数据库
            DatabaseManager.getInstance(this).saveRecord(record, new DatabaseManager.OnDataCallback<Long>() {
                @Override
                public void onSuccess(Long id) {
                    runOnUiThread(() -> {
                        Toast.makeText(TarotResultActivity.this, "占卜结果已保存到历史记录", Toast.LENGTH_SHORT).show();
                        btnSave.setText("已保存");
                        btnSave.setEnabled(false);
                    });
                }
                
                @Override
                public void onError(Exception error) {
                    runOnUiThread(() -> {
                        Toast.makeText(TarotResultActivity.this, "保存失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            });
            
        } catch (Exception e) {
            Toast.makeText(this, "保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void shareReading() {
        String shareText = "【塔罗牌占卜结果】\n\n" +
                "问题：" + question + "\n" +
                "牌阵：" + getSpreadDisplayName(spreadType) + "\n" +
                "时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(new Date(timestamp)) + "\n\n" +
                "解读：\n" + interpretation + "\n\n" +
                "—— 来自占卜大师APP";
        
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "我的塔罗牌占卜结果");
        
        startActivity(Intent.createChooser(shareIntent, "分享占卜结果"));
    }
    
    private void startNewReading() {
        // 返回到塔罗牌占卜页面
        finish();
    }
    
    private void viewDetailedCards() {
        if (cardsInfo == null || cardsInfo.isEmpty()) {
            Toast.makeText(this, "卡牌信息不完整", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 解析卡牌信息并显示详情对话框
        showCardsDetailDialog();
    }
    
    private void showCardsDetailDialog() {
        StringBuilder cardDetails = new StringBuilder();
        cardDetails.append("【抽到的塔罗牌详情】\n\n");
        
        try {
            String[] cardPairs = cardsInfo.split("\\|");
            String[] positions = TarotAlgorithm.SpreadType.valueOf(spreadType).getPositionNames();
            
            for (int i = 0; i < cardPairs.length && i < positions.length; i++) {
                String[] parts = cardPairs[i].split(",");
                if (parts.length >= 3) {
                    int cardId = Integer.parseInt(parts[0]);
                    boolean isReversed = Boolean.parseBoolean(parts[1]);
                    String positionMeaning = parts[2];
                    
                    // 从算法引擎获取标准牌库
                    List<TarotCard> deck = TarotAlgorithm.createStandardDeck();
                    TarotCard card = deck.stream()
                        .filter(c -> c.getId() == cardId)
                        .findFirst()
                        .orElse(null);
                    
                    if (card != null) {
                        cardDetails.append("【").append(positionMeaning).append("】\n");
                        cardDetails.append(card.getDisplayName());
                        cardDetails.append(isReversed ? "（逆位）" : "（正位）").append("\n");
                        cardDetails.append("关键词：").append(card.getKeywords(isReversed)).append("\n");
                        cardDetails.append("含义：").append(card.getMeaning(isReversed)).append("\n\n");
                    }
                }
            }
        } catch (Exception e) {
            cardDetails.append("解析卡牌信息时出错：").append(e.getMessage());
        }
        
        // 显示详情对话框
        new android.app.AlertDialog.Builder(this)
            .setTitle("塔罗牌详情")
            .setMessage(cardDetails.toString())
            .setPositiveButton("确定", null)
            .setNegativeButton("分享详情", (dialog, which) -> shareCardDetails(cardDetails.toString()))
            .show();
    }
    
    private void shareCardDetails(String cardDetails) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, cardDetails + "\n—— 来自占卜大师APP");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "我的塔罗牌详情");
        
        startActivity(Intent.createChooser(shareIntent, "分享塔罗牌详情"));
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
